package com.akina.matchsystem.controller;

import com.akina.matchsystem.common.BaseResponse;
import com.akina.matchsystem.common.ErrorCode;
import com.akina.matchsystem.common.ResultUtils;
import com.akina.matchsystem.exception.BusinessException;
import com.akina.matchsystem.model.domain.Team;
import com.akina.matchsystem.model.domain.User;
import com.akina.matchsystem.model.domain.UserTeam;
import com.akina.matchsystem.model.dto.TeamQuery;
import com.akina.matchsystem.model.request.*;
import com.akina.matchsystem.model.vo.TeamUserVO;
import com.akina.matchsystem.service.TeamService;
import com.akina.matchsystem.service.UserService;
import com.akina.matchsystem.service.UserTeamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/team")
//@CrossOrigin(origins = {"http://localhost:3000", "http://192.168.56.1:3000","http://8.138.130.203","http://www.akinafriend.com:3000"},allowCredentials = "true")//允许发送跨域发送cookie
@Slf4j
public class TeamController {
    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 隊伍添加
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        // 校验
        if(teamAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        //boolean save = teamService.save(team);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId= teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }


    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        // 校验
        if(teamUpdateRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean save = teamService.updateTeam(teamUpdateRequest,loginUser);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失敗");
        }

        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    public BaseResponse<Team> getTeam(long id, HttpServletRequest request) {
        // 校验
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if(team==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"查找失败");
        }

        return ResultUtils.success(team);
    }



/*    @GetMapping("/list")
    public BaseResponse<List<Team>> listTeam(TeamQuery teamQuery, HttpServletRequest request) {
        // 校验
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //Long teamId = teamQuery.getId();
        //把teamQuery传入team对象中，用Beanutils的CopyProperties

        Team team = new Team();
        BeanUtils.copyProperties(team, teamQuery);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        List<Team> teamList = teamService.list(queryWrapper);
        return ResultUtils.success(teamList);
    }*/

    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeam(TeamQuery teamQuery, HttpServletRequest request) {
        // 校验
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean admin = userService.isAdmin(request);
        List<TeamUserVO> teamList = teamService.listTeam(teamQuery,admin);//管理员可以看到私密房间
        //判断当前用户是否加入队伍
        //获取每个队伍的id
        List<Long> teamIdList = teamList.stream().map(e-> e.getId()).collect(Collectors.toList());
        QueryWrapper<UserTeam>userTeamQueryWrapper=new QueryWrapper<>();

        try {
            User loginUser = userService.getLoginUser(request);//这里可能没登录，但也要实现listTeam，所以trycatch
            userTeamQueryWrapper.eq("userId",loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            //返回所有符号条件的 UserTeam关系
            List<UserTeam>userTeamList=userTeamService.list(userTeamQueryWrapper);
            //已加入的队伍Id集合
            Set<Long> hasJoinTeamId = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(
                   team-> {
                       boolean hasJoin = hasJoinTeamId.contains(team.getId());
                       team.setHasJoin(hasJoin);
                   }
            );//team.setHasJoin 如果已经加入了队伍，就把VO里的 HasJoin给改成true。
        } catch (Exception e) {

        }
        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));


        return ResultUtils.success(teamList);
    }

    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamsByPage(TeamQuery teamQuery, HttpServletRequest request) {
        // 校验
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //Long teamId = teamQuery.getId();
        //把teamQuery传入team对象中，用Beanutils的CopyProperties
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        //分页条件
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        //查询条件
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> pageResult = teamService.page(page,queryWrapper);
        return ResultUtils.success(pageResult);
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest==null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest,user);
        return ResultUtils.success(result);
    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest==null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest,user);
        return ResultUtils.success(result);
    }

    /**
     * 删除队伍
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if(deleteRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 校验
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        boolean save = teamService.deleteTeam(id,user);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失敗");
        }

        return ResultUtils.success(true);
    }


    /**
     * 获取我创建的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamList = teamService.listTeam(teamQuery, true);
        return ResultUtils.success(teamList);
    }


    /**
     * 获取我加入的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        //把队伍id都取出来，然后传给teamQuery,在调用方法给展示出来
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamList = teamService.listTeam(teamQuery, true);
        return ResultUtils.success(teamList);
    }

}

